<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户信息提交</title>
    <!-- 引入 axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- 基础样式 -->
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f5f7fa;
            padding: 20px;
            line-height: 1.6;
        }

        .container {
            max-width: 960px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
        }

        header h1 {
            font-weight: 600;
            margin-bottom: 10px;
        }

        header p {
            color: #666;
            font-size: 14px;
        }

        /* 卡片样式（Material-like） */
        .card {
            background: #fff;
            padding: 24px 28px;
            border-radius: 12px;
            box-shadow: 0 6px 18px rgba(0,0,0,0.06);
            margin-bottom: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #444;
            font-weight: 500;
            font-size: 14px;
        }

        input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 15px;
            transition: border-color 0.3s;
        }

        input:focus {
            outline: none;
            border-color: #4299e1;
            box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
        }

        .btn {
            width: 100%;
            padding: 12px;
            background-color: #4299e1;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn:hover { background-color: #3182ce; }
        .btn-secondary { background-color: #718096; }
        .btn-secondary:hover { background-color: #4a5568; }
        .btn-danger { background-color: #e53e3e; }
        .btn-danger:hover { background-color: #c53030; }

        /* 结果提示样式 */
        #resultDiv {
            margin-top: 15px;
            padding: 12px;
            border-radius: 6px;
            font-size: 14px;
            text-align: center;
        }

        /* 用户列表样式 */
        .user-list-card { }

        .user-list-card h3 {
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }

        ul {
            list-style: none;
        }

        li {
            padding: 12px 15px;
            border-radius: 8px;
            background-color: #f9fafb;
            margin-bottom: 12px;
            color: #2d3748;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        li:hover { transform: translateX(4px); box-shadow: 0 4px 10px rgba(0,0,0,0.05); }

        .actions { display: flex; gap: 8px; }

        /* 模态框 */
        .modal {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.35);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 50;
        }
        .modal.open { display: flex; }
        .modal-content { background: #fff; border-radius: 12px; padding: 20px; width: 520px; max-width: 92vw; }
        .modal-header { font-size: 18px; font-weight: 600; margin-bottom: 12px; }

        /* 加载状态 */
        .spinner { width: 20px; height: 20px; border: 3px solid #e2e8f0; border-top-color: #4299e1; border-radius: 50%; animation: spin 1s linear infinite; }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* 响应式调整 */
        @media (max-width: 600px) {
            .form-card, .user-list-card {
                padding: 20px;
            }

            input, button[type="submit"] {
                padding: 10px 12px;
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>用户信息管理</h1>
        <p>提交用户信息或查看已有用户列表</p>
    </header>

    <!-- 表单提交区域 -->
    <div class="card">
        <form id="userForm" action="/form" method="post">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" name="username" id="username" placeholder="请输入用户名" required>
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" name="password" id="password" placeholder="请输入密码" required>
            </div>

            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" name="email" id="email" placeholder="请输入邮箱" required>
            </div>

            <button type="submit" class="btn">提交信息</button>
            <div id="resultDiv"></div>
        </form>
    </div>

    <!-- 用户列表展示区域 -->
    <div class="card user-list-card">
        <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom: 12px;">
            <h3>用户列表</h3>
            <div id="loader" style="display:none" class="spinner" aria-label="加载中"></div>
        </div>
        <div id="userList"></div>
    </div>

    <!-- 编辑模态框 -->
    <div id="editModal" class="modal" aria-hidden="true">
        <div class="modal-content">
            <div class="modal-header">编辑用户</div>
            <form id="editForm">
                <input type="hidden" id="editId" />
                <div class="form-group">
                    <label for="editUsername">用户名</label>
                    <input type="text" id="editUsername" required />
                </div>
                <div class="form-group">
                    <label for="editEmail">邮箱</label>
                    <input type="email" id="editEmail" required />
                </div>
                <div style="display:flex; gap: 8px;">
                    <button type="submit" class="btn">保存</button>
                    <button type="button" id="editCancel" class="btn btn-secondary">取消</button>
                </div>
                <div id="editResult" style="margin-top:8px"></div>
            </form>
        </div>
    </div>
</div>

<script type="module">
    import { API } from '/js/api.js';
    import { maskEmail, showResult, isValidEmail } from '/js/utils.js';

    const form = document.getElementById('userForm');
    const resultDiv = document.getElementById('resultDiv');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const emailInput = document.getElementById('email');
    const loader = document.getElementById('loader');

    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();
        const email = emailInput.value.trim();

        if (!username) return showResult(resultDiv, '用户名不能为空', 'error');
        if (!password) return showResult(resultDiv, '密码不能为空', 'error');
        if (!email || !isValidEmail(email)) return showResult(resultDiv, '请输入有效的邮箱地址', 'error');

        try {
            await API.addUser({ username, password, email });
            showResult(resultDiv, '提交成功', 'success');
            form.reset();
            await loadUserList();
        } catch (error) {
            const errorMsg = error.response?.data?.message || error.message;
            showResult(resultDiv, `提交失败：${errorMsg}`, 'error');
        }
    });

    async function loadUserList() {
        loader.style.display = 'inline-block';
        try {
            const users = await API.getUsers();
            const userListDiv = document.getElementById('userList');
            if (!users || users.length === 0) {
                userListDiv.innerHTML = '<p>暂无用户数据</p>';
                return;
            }
            let html = '<ul>';
            users.forEach(user => {
                const maskedEmail = user.email ? maskEmail(user.email) : '未设置';
                html += `<li>
                    <span>用户名: ${user.username || '未设置'}，邮箱: ${maskedEmail}</span>
                    <div class="actions">
                        <button class="btn btn-secondary" data-action="edit" data-id="${user.id}" data-username="${user.username}" data-email="${user.email || ''}">编辑</button>
                        <button class="btn btn-danger" data-action="delete" data-id="${user.id}">删除</button>
                    </div>
                </li>`;
            });
            html += '</ul>';
            userListDiv.innerHTML = html;
        } catch(err) {
            document.getElementById('userList').innerHTML = '<p style="color:#e53e3e;">获取用户列表失败，请稍后重试</p>';
        } finally {
            loader.style.display = 'none';
        }
    }

    // 事件代理：编辑与删除
    document.getElementById('userList').addEventListener('click', async (e) => {
        const target = e.target;
        if (!(target instanceof HTMLElement)) return;
        const action = target.getAttribute('data-action');
        if (action === 'edit') {
            openEditModal({
                id: Number(target.getAttribute('data-id')),
                username: target.getAttribute('data-username') || '',
                email: target.getAttribute('data-email') || ''
            });
        } else if (action === 'delete') {
            const id = Number(target.getAttribute('data-id'));
            const confirmHard = confirm('是否进行硬删除？\n选择【取消】执行软删除（需要数据库存在 is_deleted 字段）。');
            try {
                await API.deleteUser(id, confirmHard);
                await loadUserList();
            } catch (error) {
                alert('删除失败：' + (error.response?.data?.message || error.message));
            }
        }
    });

    // 编辑模态框逻辑
    const editModal = document.getElementById('editModal');
    const editForm = document.getElementById('editForm');
    const editCancel = document.getElementById('editCancel');
    const editResult = document.getElementById('editResult');
    function openEditModal(user){
        document.getElementById('editId').value = String(user.id);
        document.getElementById('editUsername').value = user.username || '';
        document.getElementById('editEmail').value = user.email || '';
        editModal.classList.add('open');
        editModal.setAttribute('aria-hidden', 'false');
    }
    editCancel.addEventListener('click', () => {
        editModal.classList.remove('open');
        editModal.setAttribute('aria-hidden', 'true');
        editResult.innerHTML = '';
    });
    editForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const id = Number(document.getElementById('editId').value);
        const username = document.getElementById('editUsername').value.trim();
        const email = document.getElementById('editEmail').value.trim();
        if (!username) return showResult(editResult, '用户名不能为空', 'error');
        if (!email || !isValidEmail(email)) return showResult(editResult, '请输入有效的邮箱地址', 'error');
        try {
            await API.updateUser(id, { username, email });
            showResult(editResult, '更新成功', 'success');
            setTimeout(async () => {
                editModal.classList.remove('open');
                editResult.innerHTML = '';
                await loadUserList();
            }, 600);
        } catch (error) {
            showResult(editResult, '更新失败：' + (error.response?.data?.message || error.message), 'error');
        }
    });

    window.onload = loadUserList;
</script>
</body>
</html>